<?php
namespace App\Controller;
use Common\Controller\AppbaseController;
use Common\Controller\AppbusinessbaseController;
use Common\Controller\AppbusinessdobaseController;
use Common\Controller\AppmemberbaseController;
use Common\Controller\AppuserbaseController;
use Think\Exception;

class BusinessloginController extends AppbaseController {

    private $token_time;
    const IS_TEST=true;
    const PREPARE_PASSWORD='123456';
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        //token过期时间
        $this->token_time=strtotime('+7 day');
    }

    //获取规则
    public function getAgreement(){
        $article=M('Posts')->where(['id'=>4])->find();
        $this->assign('article',$article['post_content']);
        $this->display('getAgreement');
    }

    //返回是否是测试
    public function isTest(){
        $this->jsonReturn(1,'获取成功',self::IS_TEST);
    }

    //测试账户
    public function cLogin(){
        $name=I('post.name');
        $password=I('password');
        if(!$name||!$password){
            $this->jsonReturn(0,'请填写账号或密码');
        }
        if(!self::IS_TEST){
            $this->jsonReturn(0,'不是测试阶段');
        }
        $user=M('Business')->where(['ceshi_name'=>$name])->find();
        if($user){
            $password=sp_password($password);
            if($password!=$user['ceshi_password']){
                $this->jsonReturn(0,'密码错误');
            }
            //创建token
            $token=lt_create_token();
            $data['token']=$token;
            $data['token_expire_time']=$this->token_time;
            $result=M('Business')->where(['id'=>$user['id']])->save($data);
            if($result!==false){
                $this->jsonReturn(1,'登录成功',['token'=>$token,'type'=>$user['type']]);
            }else{
                $this->jsonReturn(0,'登录失败');
            }
        }else{
            $this->jsonReturn(0,'账号不存在');
        }
    }

    //推广预注册
    public function pRegister(){
        $phone=I('phone');
        if(!lt_is_telephone($phone)){
            $this->jsonReturn(0,'电话格式错误');
        }
        $business=M('Business')->where(['phone'=>$phone])->field('id')->find();
        if($business){
            $this->jsonReturn(0,'电话号已存在');
        }
        //开启事物
        M('Business')->startTrans();
        try {
            $data['create_time']=time();
            $data['status']=3;
            $data['phone']=$phone;
            $data['prepare_password']=sp_password(self::PREPARE_PASSWORD);
            $data['is_prepared']=0;
            $data['openid']='';
            $uuid='@l'.uniqid();
            $data['uuid']=$uuid;
            $userId=M('Business')->add($data);
            if ($userId === false) {
                throw new Exception('注册失败！');
            }
            //生成商户二维码，内容是加密的id
            $code=lt_create_png($userId,'./data/upload/erweima/'.uniqid().'.png');
            $result=M('Business')->where(['id'=>$userId])->save(['erweima'=>$code]);
            if($result===false){
                throw new Exception('注册失败！');
            }
            M('Business')->commit();
            $this->jsonReturn(9,'请先选择商户类型',['uuid'=>$uuid]);
        } catch (Exception $e) {
            M('Business')->rollback();
            $this->jsonReturn(0,$e->getMessage());
        }
    }

    //推广预绑定登录
    public function pLogin(){
        $phone=I('phone');
        $password=I('password');
        if(!$phone){
            $this->jsonReturn(0,'手机号必须');
        }
        if(!$password){
            $this->jsonReturn(0,'密码必须');
        }
        $business=M('Business')->where(['phone'=>$phone,'prepare_password'=>sp_password($password)])->find();
        if($business){
            switch ($business['status']){
                case '3' : $this->jsonReturn(9,'请先选择商户类型',['uuid'=>$business['uuid']]);break;
                case '0' : $this->jsonReturn(0,'用户已被拉黑');break;
            }
            $token=lt_create_token();
            $data['token']=$token;
            $data['token_expire_time']=$this->token_time;
            $result=M('Business')->where(['id'=>$business['id']])->save($data);
            if($result!==false){
                $this->jsonReturn(1,'登录成功',['token'=>$token,'type'=>$business['type']]);
            }else{
                $this->jsonReturn(0,'登录失败');
            }
        }else{
            $this->jsonReturn(0,'用户不存在或密码错误');
        }
    }

    //第三方登录
    public function login(){
        $uuid=I('post.uuid');
        $openId=I('openid');
        if(!$uuid||!$openId){
            $this->jsonReturn(0,'缺少必填项');
        }
        $business=M('Business')->where(['uuid'=>$uuid])->find();
        if($business){
            switch ($business['status']){
                case '2' : $this->jsonReturn(3,'请先绑定手机号');break;
                case '3' : $this->jsonReturn(4,'请先选择商户类型');break;
                case '0' : $this->jsonReturn(0,'用户已被拉黑');break;
            }
            $token=lt_create_token();
            $data['token']=$token;
            $data['token_expire_time']=$this->token_time;
            $data['openid']=$openId;
            $result=M('Business')->where(['id'=>$business['id']])->save($data);
            if($result!==false){
                $this->jsonReturn(1,'登录成功',['token'=>$token,'type'=>$business['type']]);
            }else{
                $this->jsonReturn(0,'登录失败');
            }
        }else{
            //没用户时，注册并提示前端需要绑定手机
            //开启事物
            M('Business')->startTrans();
            try {
                $data['uuid']=$uuid;
                $data['create_time']=time();
                $data['status']=2;
                $data['openid']=$openId;
                $userId=M('Business')->add($data);
                if ($userId === false) {
                    throw new Exception('注册失败！');
                }
                //生成商户二维码，内容是加密的id
                $code=lt_create_png($userId,'./data/upload/erweima/'.uniqid().'.png');
                $result=M('Business')->where(['id'=>$userId])->save(['erweima'=>$code]);
                if($result===false){
                    throw new Exception('注册失败！');
                }
                M('Business')->commit();
                $this->jsonReturn(3,'请先绑定手机号');
            } catch (Exception $e) {
                M('Business')->rollback();
                $this->jsonReturn(0,$e->getMessage());
            }
        }
    }

    //绑定手机号
    public function bangPhone(){
        $uuid=I('post.uuid');
        $phone=I('post.phone');
        $sms=I('post.sms');
        if(!$uuid||!$phone||!$sms){
            $this->jsonReturn(0,'电话和验证码必须');
        }
        if(!lt_is_telephone($phone)){
            $this->jsonReturn(0,'电话格式不正确');
        }
        $phone_user=M('Business')->where(['phone'=>$phone])->find();
        if($phone_user&&($phone_user['is_prepared']==1)){
            $this->jsonReturn(0,'该电话已经绑定');
        }
        //预绑定商户与真正商户关联，删除微信商户
        if($phone_user&&($phone_user['is_prepared']==0)){
            $new_business=M('Business')->where(['uuid'=>$uuid,'status'=>2])->find();
            if(!$new_business){
                $this->jsonReturn(0,'商户不存在');
            }
            $this->checkPhoneCode($phone,$sms);
            $data['openid']=$new_business['openid'];
            $data['uuid']=$new_business['uuid'];
            $data['is_prepared']=1;
            $token=lt_create_token();
            $data['token']=$token;
            $data['token_expire_time']=$this->token_time;
            $result=M('Business')->where(['id'=>$phone_user['id']])->save($data);
            if($result!==false){
                M('Business')->where(['id'=>$new_business['id']])->delete();
                $this->jsonReturn(10,'绑定成功',['token'=>$token,'type'=>$phone_user['type']]);
            }else{
                $this->jsonReturn(0,'绑定失败');
            }
        }
        //正常状态的绑定手机号
        $business=M('Business')->where(['uuid'=>$uuid,'status'=>2])->find();
        if($business){
            $this->checkPhoneCode($phone,$sms);
            $data['status']=3;
            $data['phone']=$phone;
            $result=M('Business')->where(['id'=>$business['id']])->save($data);
            if($result!==false){
                $this->jsonReturn(4,'请先选择商户类型');
            }else{
                $this->jsonReturn(0,'绑定失败');
            }
        }else{
            $this->jsonReturn(0,'无此用户或该用户已完成绑定');
        }
    }

    //获取全部经营范围
    public function getScopes(){
        $uuid=I('post.uuid');
        if(!$uuid){
            $this->jsonReturn(0,'缺少必填项');
        }
        $business=M('Business')->where(['uuid'=>$uuid])->field('id')->find();
        if($business){
            //经营范围
            $scopes=M('Scope')->field('id,name')->select();
            if($scopes){
                $this->jsonReturn(1,'获取成功',$scopes);
            }else{
                $this->jsonReturn(1,'没有范围',[]);
            }
        }else{
            $this->jsonReturn(0,'无此用户');
        }
    }

    //绑定商户类型
    public function bangBusinessType(){
        $uuid=I('post.uuid');
        $type=I('post.type',0,'intval');
        $scope_id=I('post.scope_id');
        if(!$uuid||!$type||!$scope_id){
            $this->jsonReturn(0,'请选择类型');
        }
        if($type!=1 && $type!=2){
            $this->jsonReturn(0,'参数错误');
        }
        //经营范围
        $scope=M('Scope')->where(['id'=>$scope_id])->field('id')->find();
        if(!$scope){
            $this->jsonReturn(0,'经营范围不存在');
        }
        $business=M('Business')->where(['uuid'=>$uuid,'status'=>3])->find();
        if($business){
            $data['status']=4;
            $data['scope_id']=$scope_id;
            $data['type']=$type;
            $token=lt_create_token();
            $data['token']=$token;
            $data['token_expire_time']=$this->token_time;
            $result=M('Business')->where(['id'=>$business['id']])->save($data);
            if($result!==false){
                $this->jsonReturn(1,'绑定成功',['token'=>$token,'type'=>$type]);
            }else{
                $this->jsonReturn(0,'绑定商户类型失败');
            }
        }else{
            $this->jsonReturn(0,'无此用户或该用户已完成绑定');
        }
    }

    //补充资料
    public function bangData(){
        $token=I('post.token');
        $company=I('post.company');
        $identification_photo=I('post.identification_photo');
        $legal_person_photo=I('post.legal_person_photo');
        $qualify=I('post.qualify');
        if(!$company){
            $this->jsonReturn(0,'名称必填');
        }
        if(!$token||!$identification_photo){
            $this->jsonReturn(0,'缺少必传照片');
        }
        $identification_photo=$this->getSaveImageUrl($identification_photo);
        $business=lt_get_business_by_token($token);
        if($business){
            if($business['status']!=4){
                $this->jsonReturn(0,'您不能补充资料');
            }
            $now=time();
            //资质是数组
            if($qualify&&is_array($qualify)){
                foreach ($qualify as $k=>$value){
                    $qualifyData[$k]['image']=$this->getSaveImageUrl($value);
                    $qualifyData[$k]['business_id']=$business['id'];
                    $qualifyData[$k]['create_time']=$now;
                }
                M('BusinessQualify')->addAll($qualifyData);
            }
            //法人照片
            if($legal_person_photo){
                $legal_person_photo=$this->getSaveImageUrl($legal_person_photo);
                $data['legal_person_photo']=$legal_person_photo;
            }
            $data['identification_photo']=$identification_photo;
            $data['company']=$company;
            //检测是否完成装修，确定状态
            $r=$this->checkBusinessFixed($business['id']);
            $data['status']=($r===false)?5:1;
            $data['checking_time']=time();
            $result=M('Business')->where(['id'=>$business['id']])->save($data);
            if($result!==false){
                $this->jsonReturn(1,'补充资料完成');
            }else{
                $this->jsonReturn(0,'补充资料失败');
            }
        }else{
            $this->jsonReturn(2,'请先登录');
        }
    }
}